<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>toRef</title>
  <script src="../node_modules/@vue/reactivity/dist/reactivity.global.js"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
  // toRef
  const app = Vue.createApp({
    template: `<div>{{age}}</div>`,
    setup(){
      const {reactive, toRef, toRefs} = Vue;
      const data = reactive({name: 'ahhh'})

      // const {age} = toRefs(data); //如果age原本不存在, 这里返回的是undefined

      //那么如果我们想要获取某个reactive里的某个值时
      //并且希望如果它不存在,我们仍然可以获取到时
      //↓↓
      const age = toRef(data, 'age');
      console.log('age:',age);

      setTimeout(() => {
        //访问age.value 就相当于 访问 data.age
        age.value = 123; //如果使用的是 toRefs 解构的, 这里是会报错的: Uncaught TypeError: Cannot set property 'value' of undefined; 但如果使用的是 const age = toRef(data, 'age'), 这能正确响应
      }, 2000);

      return {age}
    }
  });


  const vm = app.mount('#root');
</script>
</html>
